package com.zhuss.util;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;


public class PicCheckUtil {
	
	
	public static void main(String[] args) {
		AccessToken accessToken = getAccessToken();
		CheckPic cp = getPicCheck(accessToken.getAccess_token(), null);
		System.out.println(JsonUtil.toJson(cp));
		
		/*Object obj2 = checkPick("https://121.199.36.7/pc/wpsFile/4d3ecfadb1d04a96ad21406ac4e6f730.jpg");
		System.out.println(obj2);*/
    }
	
	public static CheckPic getPicCheck(byte[] byt) {
		AccessToken accessToken = getAccessToken();
		CheckPic cp = getPicCheck(accessToken.getAccess_token(), byt);
		System.out.println(JsonUtil.toJson(cp));
		return cp;
	}

	private static AccessToken getAccessToken() {
		String str = HttpUtilEx.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c8dd744ad7974d6&secret=da4738fca2315f23ca2f6f3075575b7a");
		AccessToken obj = JsonUtil.fromJson(str, AccessToken.class);
		System.out.println(obj);
		return obj;
	}
	
	private static CheckPic getPicCheck(String accessToken, byte[] byt) {
		Map<String, Object> param = new HashMap<>();
		param.put("media", byt);
		String str = HttpUtilEx.doPostMedia("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken, param, byt);
		AccessToken obj = JsonUtil.fromJson(str, AccessToken.class);
		System.out.println(obj);
		return JsonUtil.fromJson(str, CheckPic.class);
	}
	
	
	
	/**
	 * 恶意图片过滤
	 * @return
	 */
	@SuppressWarnings("unused")
	private static Object checkPick(InputStream inputStream) {
	    try {
	        CloseableHttpClient client = null;
	        CloseableHttpResponse response = null;
	        //把代理设置到请求配置        代理IP     端口
	        HttpHost proxy = new HttpHost("121.199.36.7", 443);
	        //超时时间单位为毫秒
	        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(100).setSocketTimeout(100)
	                .setProxy(proxy).build();
	        client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
	        HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + getAccessToken());
	        request.addHeader("Content-Type", "application/octet-stream");
	        // InputStream inputStream = returnBitMap(images);
	        byte[] byt = new byte[inputStream.available()];
	        inputStream.read(byt);
	        request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));
	        response = client.execute(request);
	        HttpEntity httpEntity = response.getEntity();
	        String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
	        JSONObject jso = JSONObject.parseObject(result);
	        return jso;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return true;
	    }
	}
	
	
	/**
	 * 通过图片url返回图片Bitmap
	 *
	 * @param path
	 * @return
	 */
	@SuppressWarnings("unused")
	private static InputStream returnBitMap(String path) {
	    URL url = null;
	    InputStream is = null;
	    try {
	        url = new URL(path);
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    }
	    try {
	    	
	    	SSLContext sc = SSLContext.getInstance("SSL");
	    	sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
	        // 代理的主机
	        Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("121.199.36.7", 443));
	        HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(proxy); //利用HttpURLConnection对象,我们可以从网络中获取网页数据.
	        conn.setSSLSocketFactory(sc.getSocketFactory());
	        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
	        // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
	        conn.connect();
	        is = conn.getInputStream();    //得到网络返回的输入流

	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return is;
	}
	
	
	private static class TrustAnyTrustManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }
	
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
	
}

class AccessToken {
	private String access_token;
	
	public String getAccess_token() {
		return access_token;
	}
	
	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}
}

